package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

// https://api.matsurihi.me/mltd/v1/cards
// js getMltdCardInfo.js

func main() {

	fmt.Println("请输入mltd文件夹地址：")

	scanner := bufio.NewReader(os.Stdin)
	pathName, _, _ := scanner.ReadLine()

	//var pathName string = "F:\\IDM下载\\新建文件夹"

	nameFile, _ := os.Open(string(pathName) + "/name.txt")

	reader := bufio.NewReader(nameFile)
	nameMap := make(map[string]string)
	for true {
		line, _, _ := reader.ReadLine()
		if len(line) == 0 {
			break
		}
		nameIndex := bytes.IndexByte(line, '~')
		nameMap[string(line[0:nameIndex])] = strings.NewReplacer("/", "╱", "?", "？").Replace(string(line[nameIndex+1:]))
	}

	cardPath := string(pathName) + "/card/"
	cardDir, _ := ioutil.ReadDir(cardPath)
	for _, card := range cardDir {
		cardId0 := card.Name()
		i := strings.LastIndex(cardId0, ".")
		ex := cardId0[i:]
		var cardNewName string
		if cardId0[i-1] == 'b' {
			var trained string = "特训"
			if cardId0[i-3] == '0' {
				trained = "普通"
			}
			cardId := cardId0[0 : i-4]
			baseName := nameMap[cardId]

			i1 := strings.Index(baseName, "-")
			id := "000" + baseName[0:i1]
			cardNewName = "MLTD卡牌-" + id[len(id)-4:] + strings.Replace(baseName[i1:], "_trans_", "-"+trained+"-", 1) + ex

		} else {

			var trained string = "特训"
			if cardId0[i-1] == '0' {
				trained = "普通"
			}
			cardId := cardId0[0 : i-2]
			baseName := nameMap[cardId]

			i1 := strings.Index(baseName, "-")
			id := "000" + baseName[0:i1]
			cardNewName = "MLTD壁纸-" + id[len(id)-4:] + strings.Replace(baseName[i1:], "_trans_", "-"+trained+"-", 1) + ex
		}
		_ = os.Rename(cardPath+cardId0, cardPath+cardNewName)
		fmt.Println(cardId0 + " 被改名为 " + cardNewName)

	}
	fmt.Println("end! ")

}
